<template>
    <view class="form-box">
<!--      <u-subsection :list="list" :current="0" :active-color="'#2E8AFF'" @change="tabsChange"></u-subsection>-->
<!--      <u-tabs-swiper ref="tabs" :list="list" :is-scroll="false"  @change="tabsChange"></u-tabs-swiper>-->
        <u-form :model="form" ref="uForm">
            <u-form-item
              label="姓名"
              prop="idCardName"
              label-width="180"
              required
              v-if="swiperCurrent ==0 && isWX ==1"
            >
              <u-input
                v-model="form.idCardName"
              ></u-input>
            </u-form-item>
            <u-form-item
              label="身份证号码"
              prop="idCardNo"
              label-width="180"
              required
              v-if="swiperCurrent == 0 && isWX ==1"
            >
              <u-input
                v-model="form.idCardNo "
              ></u-input>
            </u-form-item>
            <u-form-item label="手机号码" label-width="180" prop="mobile" required v-if="swiperCurrent == 0">
                <u-input v-model="form.mobile" maxlength="11" placeholder="请输入手机号码" />
            </u-form-item>
            <u-form-item prop="smsCode" v-if="swiperCurrent == 0 && isWX != 1">
                <u-input v-model="form.smsCode" maxlength="6" placeholder="请输入手机验证码" />
                <u-toast ref="uToast"></u-toast>
                <u-verification-code :seconds="seconds" ref="uCode" @change="codeChange"
                    start-text="获取验证码"></u-verification-code>
                <view style="color: #5FC484;" @tap="getCode">{{ tips }}</view>
            </u-form-item>

            <u-form-item prop="verifyCode" v-if="swiperCurrent == 0 && isWX == 1">
              <u-input v-model="form.verifyCode" maxlength="6" placeholder="请输入手机验证码" />
              <u-toast ref="uToast"></u-toast>
              <u-verification-code :seconds="seconds" ref="uCode" @change="codeChange"
                                   start-text="获取验证码"></u-verification-code>
              <view style="color: #5FC484;" @tap="getCode2">{{ tips }}</view>
            </u-form-item>


            <u-form-item
              label="用户名"
              prop="username"
              label-width="180"
              required
              v-if="swiperCurrent == 1"
            >
              <u-input
                v-model="form.username"
              ></u-input>
            </u-form-item>
            <u-form-item
              label="密码"
              prop="password"
              label-width="180"
              required
              v-if="swiperCurrent == 1"
            >
              <u-input
                v-model="form.password"
              ></u-input>
            </u-form-item>
            <u-form-item
              label="验证码"
              prop="code"
              label-width="180"
              required
              v-if="swiperCurrent == 1"
            >
              <view style="width: 100%;display: flex;align-items: center">
                <u-input
                  style="flex: 1"
                  v-model="form.code"
                ></u-input>
                <image style="height: 64rpx;width: 180rpx;margin-left: 10rpx" :src="codeImg" @click.stop="getInfo"></image>
              </view>
            </u-form-item>


<!--          <u-form-item label="站点/大仓"  prop="deptId" required >-->
<!--            <u-input type="select" v-model="form.deptId" :placeholder="'请选择站点/大仓'"-->
<!--                     @click="showPickerMax($event)"></u-input>-->
<!--          </u-form-item>-->



        </u-form>
        <u-button type="primary" shape="square" :ripple="true" size="default" @click="submit" class="custom-btn"
            :throttle-time="5000">登录
        </u-button>
        <nui-picker ref="picker" :title="auiPicker.title" :layer="auiPicker.layer" :data="auiPicker.data"
            @callback="pickerCallback"></nui-picker>
        <u-modal v-model="showModel" content="确认注册？" @confirm="submitData" @cancel="cancel" show-cancel-button></u-modal>
<!--        <view class="tips-wrapper" v-show="showTip">-->
<!--            <p class="title">河南秒安达网络科技有限公司</p>-->
<!--            <p class="tip">秒安达从事外卖递送服务，骑手入职，需要签订送外卖的协议，秒安达会通过短信发送入职协议签订的链接，方便骑手通过短信即可直接打开小程序完成协议相关信息的签订流程，提高入职流程效率。</p>-->
<!--        </view>-->
        <u-modal v-model="showModel2" :title="showTitle" :content='showContent' :show-confirm-button="false"></u-modal>
    </view>
</template>

<script>
import store from "@/store";
import { mapGetters } from "vuex";
import { getQueryString } from "@/utils/index.js";
import nuiPicker from "@/components/picker.vue";
import { getUrlParam } from "@/utils";
import {isEmpty} from "../../../utils";
export default {
    data() {
        return {
            codeImg:'',
            list: [{
              name: '验证码登录'
            }, {
              name: '账号密码登录'
            }],
            showContent:'当前入职二维码已被禁用!',
            showModel2:false,
            showTitle:'提示',
            qrcode: {},
            form: {
                mobile: "",
                smsCode: "",
            },
            code: '',
            tips: '',
            seconds: 60,
            showModel: false,
            rules: {
                mobile: [
                    {
                        required: true,
                        message: "请输入手机号",
                        trigger: ["change", "blur"],
                    },
                    {
                        validator: (rule, value, callback) => {
                            return this.$u.test.mobile(value);
                        },
                        message: "手机号码不正确",
                        trigger: ["change", "blur"],
                    }
                ],
                smsCode: [
                    {
                        required: true,
                        message: "请输入验证码",
                        trigger: "change",
                    },
                ],
              verifyCode: [
                {
                  required: true,
                  message: "请输入验证码",
                  trigger: "change",
                },
              ],
              username: [
                {
                  required: true,
                  message: "请输入用户名",
                  trigger: "change",
                },
              ],
              password: [
                {
                  required: true,
                  message: "请输入密码",
                  trigger: "change",
                },
              ],
              code: [
                {
                  required: true,
                  message: "请输入验证码",
                  trigger: "change",
                },
              ],
              idCardName: [
                {
                  required: true,
                  message: "请输入姓名",
                  trigger: "change",
                },
              ],
              idCardNo: [
                {
                  required: true,
                  message: "请输入身份证号",
                  trigger: "change",
                },
              ],
            },
            showTip: false,
            auiPicker: {
                title: "选择站点",
                layer: null,
                data: [],
            },
            showSite: true,
            siteItem: '',
            showZhandian: false,
            urlPhone:'',
            doubleClick:false,
            swiperCurrent:0,
            isSg:false,
            isWX:0,
        };
    },
    components: {
        nuiPicker,
    },
    onLoad(option) {
      this.isWX = option.isWX
      this.isSg = JSON.parse(option.isSg?option.isSg:false)
      uni.setStorageSync("selectDeptId", " ");
      uni.setStorageSync("isCleaning"," ");
      // this.getDeptList()
    },
    mounted() {

    },
    methods: {
      async getDeptList() {
        let deptId = getQueryString("deptId") == null ? "0" : getQueryString("deptId");
        let res = await this.$api.notoken.listDept({ deptId });
        this.form.site = res.data[0].label
        this.siteItem = {
          id: res.data[0].id,
          label: res.data[0].label
        }
        this.auiPicker.data = res.data;
      },
        // tabs通知swiper切换
        tabsChange(index) {
          this.swiperCurrent = index;
          if (index == 1) {
            this.getInfo()
          }
        },
        getInfo(){
          uni.showLoading({
            title: '加载中',
            mask: true,
          });
          this.$api.dormitory.captchaImage().then((res)=>{
            uni.hideLoading();
            this.codeImg = 'data:image/jpeg;base64,'+res.img
            this.form.uuid = res.uuid
          }).catch((err)=>{
            uni.hideLoading();
          })
        },
        codeChange(text) {
            this.tips = text;
        },
        cancel() {
            this.showModel = false;
        },
        async submitData() {
          if (this.form.verifyCode != null || this.form.verifyCode != "" && this.isWX == 1) {
            let { code, msg } = await this.$api.verify.verifyPhoneCode(this.form);
            this.submitRegister();
            return
          } else {
            this.submitRegister();
          }
        },
        submit() {
            this.$refs.uForm.validate((valid) => {
                if (valid) {
                    this.showModel = true;
                } else {
                    ui.showModal({
                        title: "提示",
                        content: "验证失败",
                    });
                }
            });
        },
        async submitRegister() {
            this.doubleClick = true
            if (this.form.smsCode != null || this.form.smsCode != "" || this.form.verifyCode != null || this.form.verifyCode != "") {
              let openId = uni.getStorageSync('openId')
              this.form.openid = openId
                if (this.isWX == '1') {
                  this.form.openId = openId
                  this.form.inductionType = 3
                  this.form.phonenumber =  this.form.mobile
                  this.form.code = this.form.verifyCode
                  let { code, msg } = await this.$api.dormitory.insertSysWxUser(this.form);
                  if (code == 200) {
                    this.$u.toast('验证成功');
                    uni.reLaunch({
                      url: `/pages/HomePage/webIndex`
                    })
                  } else {
                    this.$u.toast('验证失败');
                  }
                  return
                }
                let { code, msg ,role } = await this.$api.dormitory.loginSms(this.form);
                if (code == 200) {
                    this.$u.toast('验证成功');
                    if (this.isSg == true) {
                      if (!isEmpty(openId)) {
                        let token = uni.getStorageSync("token");
                        let token2 = uni.getStorageSync("token2");
                        if (isEmpty(token) && !isEmpty(token2)) {
                          uni.setStorageSync("token",token2)
                          token = token2
                        }
                        uni.setStorageSync("cleaningName",'')
                        uni.setStorageSync("securityOfficer",'')
                        uni.setStorageSync("isAdmin",'')
                        let res2 = await this.$api.dormitory.getSysUserByOpenId(openId)

                        if (!isEmpty(res2.data) && res2.role){
                          res2.role.forEach(v =>{
                            if (v.roleKey ==  'supervisor'){
                              uni.setStorageSync("isAdmin",true)
                              uni.reLaunch({
                                url: `/pages/serve/webIndex`
                              })
                              return
                            }
                            if (v.roleKey ==  'riders_health'){
                              uni.reLaunch({
                                url: `/pages/serve/cleaning/loginWebIndex?role=3`
                              })
                              uni.setStorageSync("securityOfficer",res2.data)
                              return
                            }
                            if (v.roleKey ==  'riders_cleaning'){
                              uni.reLaunch({
                                url: `/pages/serve/cleaning/loginWebIndex?role=2`
                              })
                              uni.setStorageSync("cleaningName",res2.data)
                              return
                            }
                          })
                        }

                        // if (!isEmpty(res2.data) && res2.role && res2.role[0].roleKey ==  'supervisor'){
                        //   uni.setStorageSync("isAdmin",true)
                        // }
                        //
                        // if (!isEmpty(res2.data) && res2.role && res2.role[0].roleKey ==  'riders_health'){
                        //   uni.reLaunch({
                        //     url: `/pages/serve/cleaning/loginWebIndex?role=3`
                        //   })
                        //   uni.setStorageSync("securityOfficer",res2.data)
                        //   return
                        // }
                        //
                        // if (!isEmpty(res2.data) && res2.role && res2.role[0].roleKey ==  'riders_cleaning'){
                        //   uni.reLaunch({
                        //     url: `/pages/serve/cleaning/loginWebIndex?role=2`
                        //   })
                        //   uni.setStorageSync("cleaningName",res2.data)
                        //   return
                        // }
                      }
                      // if (role == 'supervisor') {
                      //   uni.setStorageSync("isAdmin",true)
                      // } else if (role == 'riders_cleaning') {
                      //   uni.reLaunch({
                      //     url: `/pages/serve/cleaning/loginWebIndex?role=2`
                      //   })
                      // } else if (role == 'riders_health')  {
                      //   uni.reLaunch({
                      //     url: `/pages/serve/cleaning/loginWebIndex?role=3`
                      //   })
                      // }

                    } else {
                      uni.reLaunch({
                        url: `/pages/HomePage/webIndex`
                      })
                    }
                } else {
                    this.$u.toast('验证失败');
                }
            } else {
                this.$u.toast('验证码为空');
            }
        },
        //显示picker多级联动弹窗
        showPickerMax(e) {
            this.auiPicker.layer = null;
            this.$refs.picker.open();
        },
        //picker多级联动回调
        pickerCallback(e) {
            let data = e.data;
            this.siteItem = data[data.length - 1];
            this.form.site = this.siteItem.label;
            uni.setStorageSync("selectDeptId", this.siteItem.id);
        },
        async getCode() {
            if (!this.$u.test.mobile(this.form.mobile)) {
                this.$u.toast('请输入正确的手机号');
            } else {
                if (this.$refs.uCode.canGetCode) {
                    // 向后端请求验证码
                    let { code, msg ,uuid ,supervisor } = await this.$api.dormitory.smsCode(this.form);
                    // if (supervisor == 1) {
                    //   this.isSg = true
                    // }
                    if (code == 200) {
                        this.form.uuid = uuid
                        uni.hideLoading();
                        // 这里此提示会被this.start()方法中的提示覆盖
                        this.$u.toast('验证码已发送');
                        // 通知验证码组件内部开始倒计时
                        this.$refs.uCode.start();
                    } else {
                        this.$u.fail('发送失败，请重试')
                    }
                } else {
                    this.$u.toast('倒计时结束后再发送');
                }
            }
        },
        async getCode2() {
        if (!this.$u.test.mobile(this.form.mobile)) {
          this.$u.toast('请输入正确的手机号');
        } else {
          if (this.$refs.uCode.canGetCode) {
            // 向后端请求验证码
            let { code, msg ,uuid ,supervisor } = await this.$api.verify.phoneCode(this.form);
            if (code == 200) {
              uni.hideLoading();
              // 这里此提示会被this.start()方法中的提示覆盖
              this.$u.toast('验证码已发送');
              // 通知验证码组件内部开始倒计时
              this.$refs.uCode.start();
            } else {
              this.$u.fail('发送失败，请重试')
            }
          } else {
            this.$u.toast('倒计时结束后再发送');
          }
        }
      },
        // 查询当前提示
        async getCustomCode() {
            if (!this.qrCodeId) {
                return
            }
            const res = await this.$api.inductionCode.getCode(this.qrCodeId)
            if (res && res.code === 200) {
                this.qrcode = res.data
                if (this.qrcode && this.qrcode.deleted === true) {
                    store.commit("UPDATE_ROUTEURL", "/pages/disable/index");
                }
            }
        },
        end() {
            this.$u.toast('倒计时结束');
        },
        start() {
            this.$u.toast('倒计时开始');
        },
        // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
        onReady() {
            this.$refs.uForm.setRules(this.rules);
            // // 判断是否在微信小程序中打开
            // if (window.__wxjs_environment === 'miniprogram') {
            //     this.showTip = true
            // }
            // // 查询当前二维码
            // this.getCustomCode()
        }
    },
    computed: {
        ...mapGetters(['qrCodeType', 'qrCodeId']),
    }
};
</script>

<style lang="scss" scoped>
.top-tip-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    width: 100%;
    height: 24px;
    color: white;
    font-weight: 600;
    font-size: 13px;
    background-color: #2979FF;
}

.form-box {
    box-sizing: border-box;
    padding: 20px;
}

.custom-btn {
    margin: 15px auto;
    left: 50%;
    transform: translateX(-50%);
}

.tips-wrapper {
    width: 90%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: fixed;
    bottom: 32px;

    .title {
        font-weight: bold;
        font-size: 14px;
    }

    .tip {
        margin-top: 6px;
        font-size: 12px;
    }

}
</style>
